package com.xms.sdk.data;

import com.xms.datacore.SqlDescriptor;
import com.xms.datacore.provider.IDataRepositoryBase;
import com.xms.schema.entity.Attribute;
import com.xms.schema.entity.Entity;
import com.xms.schema.entity.RelationShip;
import com.xms.schema.extension.AttributeExt;
import com.xms.sdk.core.query.AttributeAggregateExpression;
import com.xms.utils.CollectionUtil;
import com.xms.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * FieldValueUpdater
 * </p>
 *
 * @author migo
 * @since 2021/10/17
 */
@Service
public class FieldValueUpdater implements IFieldValueUpdater{
    private IDataRepositoryBase _dataRepositoryBase;
    @Autowired
    public void FieldValueUpdater(IDataRepositoryBase dataRepositoryBase) {
        _dataRepositoryBase = dataRepositoryBase;
    }

    @Override
    public boolean updateSummaryValue(Entity entityMetadata, com.xms.core.data.Entity data, Attribute summaryField, RelationShip relationShipMetadata, AttributeAggregateExpression aggExp) throws SQLException {
        String sql = String.format("UPDATE %s SET %s=(SELECT %s(%s) FROM %s WHERE %s=?) WHERE %s=?"
                , summaryField.getEntityname()
                , summaryField.getName()
                , aggExp.Aggregate
                , aggExp.Field
                , aggExp.EntityName
                , relationShipMetadata.getReferencedattributename()
                , relationShipMetadata.getReferencedattributename());

        _dataRepositoryBase.execute(new SqlDescriptor(sql, data.getStringValue(relationShipMetadata.getReferencingattributename())));
        return true;
    }

    @Override
    public boolean updateFormulaValue(String entityName, List<Attribute> attributes, UUID recordId) throws SQLException {
        String sql = String.format("UPDATE %s SET ", entityName);
        List<String> sets = new ArrayList<>();
        for (Attribute attr : attributes)
        {
            if (StringUtil.notEmpty(attr.getFormulaexpression()))
            {
                sets.add(String.format("%s=%s", attr.getName(), attr.getFormulaexpression()));
            }
        }
        if (CollectionUtil.notEmpty(sets))
        {
            sql += String.join(",", sets);
            sql += String.format(" WHERE %s=?", attributes.stream().filter(x -> AttributeExt.typeIsPrimaryKey(x)).findFirst().get());
            _dataRepositoryBase.execute(new SqlDescriptor(sql, recordId));
        }
        return true;
    }
}
